import 'dart:io';
import 'dart:math';
import 'package:path_provider/path_provider.dart';

class AppCacheManager {
  // 获取总缓存大小
  static Future<String> getTotalCacheSizeFormat() async {
    return formatSize(await getTotalCacheSize());
  }

  // 获取总缓存大小
  static Future<int> getTotalCacheSize() async {
    int totalSize = 0;
    //先统计缓存目录
    totalSize += await _getDirectorySize(await getTemporaryDirectory());
    // 添加其他自定义缓存目录（示例）
    final appSupportDir = await getApplicationSupportDirectory();
    final customCacheDir = Directory('${appSupportDir.path}/custom_cache');
    totalSize += await _getDirectorySize(customCacheDir);

    return totalSize;
  }

  // 计算目录大小
  static Future<int> _getDirectorySize(Directory dir) async {
    if (!await dir.exists()) return 0;
    int size = 0;
    final files = dir.list(recursive: true, followLinks: false);
    await for (var entity in files) {
      if (entity is File) {
        size += await entity.length();
      }
    }
    return size;
  }

  // 清空所有缓存
  static Future<void> clearAllCache() async {
    final tempDir = await getTemporaryDirectory();
    await _deleteDirectory(tempDir);

    final appSupportDir = await getApplicationSupportDirectory();
    final customCacheDir = Directory('${appSupportDir.path}/custom_cache');
    await _deleteDirectory(customCacheDir);
  }

  // 删除目录并重新创建
  static Future<void> _deleteDirectory(Directory dir) async {
    if (await dir.exists()) {
      try {
        await dir.delete(recursive: true);
      } catch (e) {
        print('删除失败: $e');
      }
      await dir.create(); // 重新创建目录
    }
  }

  // 格式化缓存大小
  static String formatSize(int bytes) {
    if (bytes <= 0) return '0 B';
    const suffixes = ['B', 'KB', 'MB', 'GB', 'TB'];
    int i = (log(bytes) / log(1024)).floor();
    return '${(bytes / pow(1024, i)).toStringAsFixed(2)} ${suffixes[i]}';
  }
}
